<?php

/**
 * @author Cesar Augustus Silva <cesaraugustussilva@linuxmail.org>
 * @copyright Copyright (c) 2013, Cesar Augustus Silva
 * @license http://www.gnu.org/licenses/gpl.html GNU GPL v3.0
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <­http://www.gnu.org/licenses/>.
 */

if ($_POST) {
    require_once(dirname(__FILE__).'/../config/config.inc.php');
    if ($_POST['cpanel'] == 'createad') {
        $data = array(
            'modelyear' => $_POST['modelyear'],
            'firstreg' => $_POST['firstreg'],
            'engine' => $_POST['engine'],
            'price' => Util::parse_float($_POST['price']),
            'discount' => Util::parse_float($_POST['discount']),
            'funded' => $_POST['funded'],
            'inputvalue' => Util::parse_float($_POST['inputvalue']),
            'parcelsquantity' => $_POST['parcelsquantity'],
            'parcelvalue' => Util::parse_float($_POST['parcelvalue']),
            'new' => $_POST['new'],
            'id_fuel' => (!empty($_POST['fuel'])) ? $_POST['fuel'] : NULL,
            'id_color' => $_POST['color'],
            'doors' => $_POST['doors'],
            'id_shield' => (!empty($_POST['shield'])) ? $_POST['shield'] : NULL,
            'id_exchange' => (!empty($_POST['exchange'])) ? $_POST['exchange'] : NULL,
            'id_version' => (!empty($_POST['version'])) ? $_POST['version'] : NULL,
            'plate' => str_replace('-', '', $_POST['plate']),
            'km' => $_POST['km'],
            'renavam' => $_POST['renavam'],
            'owner' => $_POST['owner'],
            'cpfcnpj_owner' => preg_replace('/\D/s', '', $_POST['cpfcnpj_owner']),
            'video' => $_POST['video'],
            'observations' => $_POST['observations']
        );
        if (!isset($_POST['id'])) {
            $data['dateinclusion'] = date('Y-m-d');
            $data['id_model'] = $_POST['model'];
            $id = DbSet::vehicles($data);
            
            $session = new Session('account');
            if ($session->type == 'F') {
                $data = array(
                    'id_status' => 1,
                    'id_plan' => $_POST['plan'],
                    'id_customer' => $session->id,
                    'id_vehicle' => $id
                );
                $id_customer_vehicle = DbSet::customers_vehicles($data);
            }
            else {
                $data = array(
                    'id_status' => 3,
                    'id_enterprise' => $session->id,
                    'id_vehicle' => $id
                );
                DbSet::enterprises_vehicles($data);
            }
        }
        else {
            $id = $_POST['id'];
            DbSet::vehicles($data, $id);
            
            if (!empty($_POST['pictures-excluded'])) {
                $pictures_excluded = explode(',', $_POST['pictures-excluded']);
                foreach (DbGet::vehicle_pictures($id) as $picture) {
                    if (in_array($picture->id, $pictures_excluded)) {
                        if (file_exists(_VHC_DIR_.'view/'.$picture->filename))
                            unlink(_VHC_DIR_.'view/'.$picture->filename);
                        if (file_exists(_VHC_DIR_.'deal/'.$picture->filename))
                            unlink(_VHC_DIR_.'deal/'.$picture->filename);
                        if (file_exists(_VHC_DIR_.'last-updated/'.$picture->filename))
                            unlink(_VHC_DIR_.'last-updated/'.$picture->filename);
                        if (file_exists(_VHC_DIR_.'search/'.$picture->filename))
                            unlink(_VHC_DIR_.'search/'.$picture->filename);
                    }
                }
                DbRem::vehicle_pictures($pictures_excluded);
            }
        }
        
        DbRem::vehicle_details($id);
        for ($i = 0; $i < count($_POST['details']) ; $i++) {
            $data = array(
                'id_vehicle' => $id,
                'id_detail' => $_POST['details'][$i]
            );
            DbSet::vehicles_details($data);
        }
        
        DbRem::vehicle_differentials($id);
        for ($i = 0; $i < count($_POST['differentials']) ; $i++) {
            $data = array(
                'id_vehicle' => $id,
                'id_differential' => $_POST['differentials'][$i]
            );
            DbSet::vehicles_differentials($data);
        }
        
        foreach ($_FILES['pictures']['tmp_name'] as $tmp_name) {
            if (empty($tmp_name))
                break;
            $filename = md5(uniqid(time())).'.jpg';
            list($img_width, $img_height, $imagetype) = @getimagesize($tmp_name);
            
            switch ($imagetype) {
                case IMAGETYPE_GIF:
                    $src_img = @imagecreatefromgif($tmp_name);
                    break;
                case IMAGETYPE_JPEG:
                    $src_img = @imagecreatefromjpeg($tmp_name);
                    break;
                case IMAGETYPE_PNG:
                    $src_img = @imagecreatefrompng($tmp_name);
                    break;
            }
            
            $thumbs = array(
                array(
                    'width' => 400,
                    'height' => 300,
                    'dir' => _VHC_DIR_.'view/'
                ),
                array(
                    'width' => 310,
                    'height' => 210,
                    'dir' => _VHC_DIR_.'deal/'
                ),
                array(
                    'width' => 120,
                    'height' => 77,
                    'dir' => _VHC_DIR_.'last-updated/'
                ),
                array(
                    'width' => 130,
                    'height' => 100,
                    'dir' => _VHC_DIR_.'search/'
                )
            );
            
            foreach ($thumbs as $thumb) {
                $width = $thumb["width"];
                $height = $thumb["height"];
                $scale = max(
                    $width / $img_width,
                    $height / $img_height
                );
                if ($scale > 1)
                    $scale = 1;
                $new_width = $img_width * $scale;
                $new_height = $img_height * $scale;
                $new_x = ($new_width > $width) ? $new_width - $width : 0;
                $new_y = ($new_height > $height) ? $new_height - $height : 0;
                $new_img = imagecreatetruecolor($new_width-$new_x, $new_height-$new_y);
                if ($src_img) {
                    imagecopyresampled(
                        $new_img,
                        $src_img,
                        0 - $new_x / 2,
                        0 - $new_y / 2,
                        0, 0,
                        $new_width,
                        $new_height,
                        $img_width,
                        $img_height
                    );
                    if (file_exists($thumb['dir'].'logo.png')) {
                        $logo_img = @imagecreatefrompng($thumb['dir'].'logo.png');
                        $logo_width = imagesx($logo_img);
                        $logo_height = imagesy($logo_img);
                        imagecopy(
                            $new_img,
                            $logo_img,
                            5,
                            $height - $logo_height - 5,
                            0, 0,
                            $logo_width,
                            $logo_height
                        );
                    }
                    imagejpeg($new_img, $thumb['dir'].$filename);
                }
                imagedestroy($new_img);
            }
            imagedestroy($src_img);
            
            if (file_exists($thumbs[0]['dir'].$filename)) {
                $data = array(
                    'id_vehicle' => $id,
                    'filename' => $filename
                );
                DbSet::vehicles_pictures($data);
            }
        }
        header('Location: '.__BASE_URI__.'painel/gerenciar-anuncios');
    }
    elseif ($_POST['cpanel'] == 'removead') {
        $id = $_POST['id_vehicle'];
        foreach (DbGet::vehicle_pictures($id) as $picture) {
            if (file_exists(_VHC_DIR_.'view/'.$picture->filename))
                unlink(_VHC_DIR_.'view/'.$picture->filename);
            if (file_exists(_VHC_DIR_.'deal/'.$picture->filename))
                unlink(_VHC_DIR_.'deal/'.$picture->filename);
            if (file_exists(_VHC_DIR_.'last-updated/'.$picture->filename))
                unlink(_VHC_DIR_.'last-updated/'.$picture->filename);
            if (file_exists(_VHC_DIR_.'search/'.$picture->filename))
                unlink(_VHC_DIR_.'search/'.$picture->filename);
        }
        DbRem::vehicle($id);
                
        $addr = DbGet::miscellaneous('email_service');
        $subject = '[Remoção do anúncio] - '.$_POST['name'];

        $message = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">'."\n";
        $message .= '<HTML>'."\n";
        $message .= '    <HEAD>'."\n";
        $message .= '        <META HTTP-EQUIV=\"CONTENT-TYPE\" CONTENT=\"text/html; charset=utf-8\">'."\n";
        $message .= '    </HEAD>'."\n";
        $message .= '    <BODY LANG=\"pt-BR\" DIR=\"LTR\">'."\n";
        $message .= '        <p>Nome: '.$_POST['name'].'</p>'."\n";
        $message .= '        <p>Motivo da Remoção: '.$_POST['reason'].'</p>'."\n";
        $message .= '    </BODY>'."\n";
        $message .= '</HTML>'."\n";
        
        $email_control = DbGet::miscellaneous('email_control');
        $headers = 'MIME-Version: 1.1'."\n";
        $headers .= 'Content-type: text/html; charset=utf-8'."\n";
        $headers .= 'Content-Transfer-Encoding: 8bit'."\n";
        $headers .= 'From: "Goiautos" <'.$email_control.'>'."\n";
        $headers .= 'Reply-To: "Goiautos" <'.$email_control.'>'."\n";
        $headers .= 'Return-Path: '.$email_control."\n";
        
        mail($addr,$subject,$message,$headers);
        
        header('Location: '.__BASE_URI__.'painel/gerenciar-anuncios');
    }
    elseif ($_POST['cpanel'] == 'register') {
        $data = array(
            'id_city' => $_POST['city'],
            'cep' => preg_replace('/\D/s', '', $_POST['cep']),
            'address' => $_POST['address'],
            'number' => $_POST['number'],
            'district' => $_POST['district'],
            'complement' => $_POST['complement'],
            'contacts' => $_POST['contacts'],
            'fancyname' => $_POST['fancyname'],
            'corporatename' => $_POST['corporatename'],
            'website' => preg_replace('/^http:\/\//s', '', $_POST['website'])
        );
        if (isset($_POST['cpf'])) {
            $data['name'] = $_POST['name'];
            if (!DbSet::customers($data, $_POST['id']))
                die('ERROR');
        }
        else {
            $data['fancyname'] = $_POST['fancyname'];
            $data['corporatename'] = $_POST['corporatename'];
            if (!DbSet::enterprises($data, $_POST['id']))
                die('ERROR');
        }
        
        if (!empty($_POST['phones-excluded']))
            DbRem::phones(explode(',', $_POST['phones-excluded']));
        
        for ($i = 0; $i < count($_POST['phone-number']) ; $i++)
            if (!empty($_POST['phone-number'][$i])) {
                $data = array(
                    'id_type' => $_POST['phone-type'][$i],
                    'areacode' => $_POST['phone-areacode'][$i],
                    'number' => ereg_replace('-', '', $_POST['phone-number'][$i])
                );
                if (isset($_POST['cpf'])) {
                    if ($_POST['phone-id'][$i])
                        DbSet::customers_phones($_POST['id'], $data, $_POST['phone-id'][$i]);
                    else
                        DbSet::customers_phones($_POST['id'], $data);
                }
                else {
                    if ($_POST['phone-id'][$i])
                        DbSet::enterprises_phones($_POST['id'], $data, $_POST['phone-id'][$i]);
                    else
                        DbSet::enterprises_phones($_POST['id'], $data);
                }
            }
    }
    elseif ($_POST['cpanel'] == 'pictures') {
        if (!empty($_POST['filepicture-excluded'])) {
            if (file_exists(_ETP_DIR_.'normal/'.$_POST['filepicture-excluded']))
                unlink(_ETP_DIR_.'normal/'.$_POST['filepicture-excluded']);
            if (file_exists(_ETP_DIR_.'thumb/'.$_POST['filepicture-excluded']))
                unlink(_ETP_DIR_.'thumb/'.$_POST['filepicture-excluded']);
        }
        if (!empty($_POST['filebrand-excluded'])) {
            if (file_exists(_ETP_DIR_.'logo/'.$_POST['filebrand-excluded']))
                unlink(_ETP_DIR_.'logo/'.$_POST['filebrand-excluded']);
        }
        
        $pictures[0] = $_FILES['filepicture']['tmp_name'];
        $pictures[1] = $_FILES['filebrand']['tmp_name'];
        $filename = array();
        foreach ($pictures as $key => $tmp_name) {
            $filename[$key] = md5(uniqid(time())).'.jpg';
            if (!empty($tmp_name)) {
                list($img_width, $img_height, $imagetype) = @getimagesize($tmp_name);

                switch ($imagetype) {
                    case IMAGETYPE_GIF:
                        $src_img = @imagecreatefromgif($tmp_name);
                        break;
                    case IMAGETYPE_JPEG:
                        $src_img = @imagecreatefromjpeg($tmp_name);
                        break;
                    case IMAGETYPE_PNG:
                        $src_img = @imagecreatefrompng($tmp_name);
                        break;
                }

                $thumbs = array(
                    array(
                        array(
                            'width' => 269,
                            'height' => 189,
                            'dir' => _ETP_DIR_.'normal/'
                        ),
                        array(
                            'width' => 128,
                            'height' => 88,
                            'dir' => _ETP_DIR_.'thumb/'
                        )
                    ),
                    array(
                        array(
                            'width' => 178,
                            'height' => 48,
                            'dir' => _ETP_DIR_.'logo/'
                        )
                    )
                );

                foreach ($thumbs[$key] as $thumb) {
                    $width = $thumb["width"];
                    $height = $thumb["height"];
                    $scale = max(
                        $width / $img_width,
                        $height / $img_height
                    );
                    if ($scale > 1)
                        $scale = 1;
                    $new_width = $img_width * $scale;
                    $new_height = $img_height * $scale;
                    $new_x = ($new_width > $width) ? $new_width - $width : 0;
                    $new_y = ($new_height > $height) ? $new_height - $height : 0;
                    $new_img = imagecreatetruecolor($new_width-$new_x, $new_height-$new_y);
                    if ($src_img) {
                        imagecopyresampled(
                            $new_img,
                            $src_img,
                            0 - $new_x / 2,
                            0 - $new_y / 2,
                            0, 0,
                            $new_width,
                            $new_height,
                            $img_width,
                            $img_height
                        );
                        imagejpeg($new_img, $thumb['dir'].$filename[$key]);
                    }
                    imagedestroy($new_img);
                }
                imagedestroy($src_img);
            }
        }
        
        $data = array();
        if (file_exists($thumbs[0][0]['dir'].$filename[0]))
            $data = array_merge($data, array('filepicture' => $filename[0]));
        elseif (!empty($_POST['filepicture-excluded']))
            $data = array_merge($data, array('filepicture' => null));
        if (file_exists($thumbs[1][0]['dir'].$filename[1]))
            $data = array_merge($data, array('filebrand' => $filename[1]));
        elseif (!empty($_POST['filebrand-excluded']))
            $data = array_merge($data, array('filebrand' => null));
        if (!empty($data))
            DbSet::enterprises($data, $_POST['id']);
        header('Location: '.__BASE_URI__.'painel/imagens-da-empresa');
    }
    elseif ($_POST['cpanel'] == 'chpasswd') {
        $curpasswd = md5($_POST['current-password']);
        $newpasswd = md5($_POST['new-password']);
        $session = new Session('account');
        if ($curpasswd == $session->password) {
            $data = array('password' => $newpasswd);
            if (DbSet::accounts($data, $session->id, $session->type))
                $session->password = $newpasswd;
            else
                echo 'ERROR';
        }
        else
            echo 'INVALID';
    }
}